package cn.jiyun.service.impl;

import cn.jiyun.mapper.DepartmentMapper;
import cn.jiyun.pojo.Department;
import cn.jiyun.service.DepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
* @author Lenovo
* @description 针对表【department】的数据库操作Service实现
* @createDate 2024-10-28 16:53:27
*/
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department>
    implements DepartmentService{

    @Override
    public Page findPage(Integer pageNum, Integer pageSize,Department department) {
        Page page=new Page(pageNum,pageSize);
        LambdaQueryWrapper<Department> qr = new LambdaQueryWrapper<>();
        qr.like(!StringUtils.isEmpty(department.getName()),Department::getName,department.getName());
        qr.eq(!StringUtils.isEmpty(department.getState()),Department::getState,department.getState());
        Page selectPage = baseMapper.selectPage(page, qr);
        return selectPage;
    }

    @Override
    public List<Department> tab(Department department) {
        LambdaQueryWrapper<Department> qr = new LambdaQueryWrapper<>();
        List<Department> departmentList = baseMapper.selectList(qr);
        List<Department> DepartmentTree = buildDepartment(departmentList);
        return DepartmentTree;
    }

    private List<Department> buildDepartment(List<Department> departmentList) {
        List<Department> tree = new ArrayList<>();
        for (Department department : departmentList){
            if(department.getPid() == 0){
                tree.add(getChild(department, departmentList));
            }
        }
        return tree;
    }

    private Department getChild(Department department, List<Department> departmentList) {
        department.setChildren(new ArrayList<Department>());
        for (Department per : departmentList){
            if(per.getPid().longValue()==department.getId().longValue()){
                department.getChildren().add(getChild(per, departmentList));
            }
        }
        if(department.getChildren().size()==0){
            department.setChildren(null);
        }
        return department;
    }

}




